﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameLibrary.AI
{
    using Unit;

    public static class FightSimulator
    {
        /// <summary>
        /// Give fighting result of two unit.
        /// Return remaining hp of both unit.
        /// </summary>
        /// <param name="attacker"></param>
        /// <param name="defender"></param>
        /// <param name="attackerRemainingHp"></param>
        /// <param name="defenderRemainingHp"></param>
        public static void GetResult(
            UnitInfo attacker,
            UnitInfo defender,
            out float attackerRemainingHp,
            out float defenderRemainingHp)
        {
            attackerRemainingHp = attacker.Current.HP;
            defenderRemainingHp = defender.Current.HP;

            bool defenderCanReachAttacker = false;
            if (defender.Template.AttackRange >= attacker.Template.AttackRange)
                defenderCanReachAttacker = true;

            while (attackerRemainingHp > 0
                && defenderRemainingHp > 0)
            {
                // attacker's turn
                float diff = (float)attacker.Current.Attack - (float)defender.Current.Defence;
                if (diff >= 0)
                    defenderRemainingHp -= diff + 1;
                else
                    if (defenderCanReachAttacker == true)
                        attackerRemainingHp += diff; // damaged by defender's defence action
                
                //check whether either party is died
                if(attackerRemainingHp <=0 || defenderRemainingHp<=0)
                    break;

                //defender's turn
                if (defenderCanReachAttacker == true)
                {
                    diff = defender.Current.Attack - attacker.Current.Defence;
                    if (diff >= 0)
                        attackerRemainingHp -= diff + 1;
                    else
                        defenderRemainingHp += diff;
                }
            }
        }
    }
}
